from flask import request
from marshmallow import ValidationError
from api.database import db
from api.apps.author import author_bp
from api.apps.author.models import Author
from api.apps.author.schemas import AuthorSchema
from api.apps.utils.responses import response_with
from api.apps.utils import responses as resp
from api.apps.utils.logging_config import setup_logging

# 导入日志记录器
logger = setup_logging()


@author_bp.route('/', methods=['POST'])
def create_author():
  """
          新建作者接口
          ---
          parameters:
              - in: body
                name: body
                schema:
                  required:
                      - name
                  properties:
                      name:
                          type: string
                          description: 作者名
                          default: ""
          responses:
              201:
                  description: 新增作者成功
                  schema:
                      properties:
                          code:
                              type: string
              422:
                  description: 新增作者失败
                  schema:
                      properties:
                          code:
                              type: string
                          message:
                              type: string
  """
  try:
    # 从请求中获取数据
    data = request.get_json()
    logger.info(f"data is {data}")
    # 使用 AuthorSchema 反序列化 JSON 数据为 Author 模型实例。
    author_schema = AuthorSchema()
    author = author_schema.load(data)
    # 将反序列化后的数据保存到数据库中，并序列化为 JSON 格式。
    result = author_schema.dump(author.create())
    # 返回 JSON 响应，状态码为 201（表示资源创建成功）。
    return response_with(resp.SUCCESS_201, value={"author": result})
  except ValidationError as e:
    # 数据验证失败，返回 400 错误
    logger.error(f"ValidationError is {e}")
    return response_with(resp.BAD_REQUEST_400)
  except Exception as e:
    # 捕获其他异常并返回 500 错误
    logger.error(f"other_err is {e}")
    db.session.rollback()  # 回滚事务
    return response_with(resp.SERVER_ERROR_500)


@author_bp.route('/', methods=['GET'])
def get_author_list():
  fetched = Author.query.all()
  author_schema = AuthorSchema(many=True, only=['name', 'id'])
  authors = author_schema.dump(fetched)
  return response_with(resp.SUCCESS_200, value={"authors": authors})


@author_bp.route('/<int:author_id>', methods=['GET'])
def get_author_detail(author_id):
  fetched = Author.query.get_or_404(author_id)
  author_schema = AuthorSchema()
  author = author_schema.dump(fetched)
  return response_with(resp.SUCCESS_200, value={"author": author})


@author_bp.route('/<int:id>', methods=['PUT'])
def update_author_detail(id):
  data = request.get_json()
  get_author = Author.query.get_or_404(id)
  get_author.name = data['name']
  db.session.add(get_author)
  db.session.commit()
  author_schema = AuthorSchema()
  author = author_schema.dump(get_author)
  return response_with(resp.SUCCESS_200, value={"author": author})


@author_bp.route('/<int:id>', methods=['PATCH'])
def modify_author_detail(id):
  data = request.get_json()
  get_author = Author.query.get(id)
  if data.get('name'):
    get_author.name = data['name']
  db.session.add(get_author)
  db.session.commit()
  author_schema = AuthorSchema()
  author = author_schema.dump(get_author)
  return response_with(resp.SUCCESS_200, value={"author": author})


@author_bp.route('/<int:id>', methods=['DELETE'])
def delete_author(id):
  get_author = Author.query.get_or_404(id)
  logger.info(f"author is {get_author}")
  db.session.delete(get_author)
  db.session.commit()
  print(response_with(resp.SUCCESS_200))
  return response_with(resp.SUCCESS_200)
